package com.hulk.dryad.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.persistence.entity.SysUserPost;
import com.hulk.dryad.persistence.mapper.SysUserPostMapper;
import com.hulk.dryad.admin.service.SysUserPostService;
import com.hulk.dryad.manage.boot.injector.impl.SuperServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户与岗位关联表 服务实现类
 * </p>
 *
 * @author hulk
 * @since 2021-04-01
 */
@Service
public class SysUserPostServiceImpl extends SuperServiceImpl<SysUserPostMapper, SysUserPost> implements SysUserPostService {

	@Override
	@Cacheable(value = CacheConstants.POST_DETAILS + "#60s", key = "#userId", unless = "#result == null")
	public List<SysUserPost> getListByUserId(Long userId) {
		Wrapper<SysUserPost> wrapper = new LambdaQueryWrapper<SysUserPost>()
				.eq(SysUserPost::getUserId, userId);
		return super.list(wrapper);
	}

	@Override
	public boolean saveByUserIdAndPostIds(Long userId, List<Long> postIds) {
		List<SysUserPost> userRoleList = postIds.stream()
				.map(postId -> {
					SysUserPost userPost = new SysUserPost();
					userPost.setUserId(userId);
					userPost.setPostId(postId);
					return userPost;
				})
				.distinct()
				.collect(Collectors.toList());
		return super.saveBatch(userRoleList);
	}

	@Override
	@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#userId", allEntries = true)
	public boolean removeByUserId(Long userId) {
		Wrapper<SysUserPost> wrapper = new LambdaQueryWrapper<SysUserPost>()
				.eq(SysUserPost::getUserId, userId);
		return super.remove(wrapper);
	}

	@Override
	public boolean removeByUserIds(Set<Long> userIds) {
		Wrapper<SysUserPost> wrapper = new LambdaQueryWrapper<SysUserPost>()
				.in(SysUserPost::getUserId, userIds);
		return super.remove(wrapper);
	}

	@Override
	public boolean removeByPostIds(Set<Long> postIds) {
		Wrapper<SysUserPost> wrapper = new LambdaQueryWrapper<SysUserPost>()
				.in(SysUserPost::getPostId, postIds);
		return super.remove(wrapper);
	}

	@Override
	public List<SysUserPost> getListByPostIds(Collection<Long> postIds) {
		Wrapper<SysUserPost> wrapper = new LambdaQueryWrapper<SysUserPost>()
				.in(SysUserPost::getPostId, postIds);
		return super.list(wrapper);
	}
	@Override
	@Cacheable(value = CacheConstants.POST_ID_DETAILS + "#60s", key = "#userId", unless = "#result == null")
	public Set<Long> getPostIdsByUserId(Long  userId) {
		Set<Long> userPostIds = this.getListByUserId(userId).stream().map(SysUserPost::getPostId).collect(Collectors.toSet());
		return userPostIds;
	}

}
